package org.yankun.exam4j.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.yankun.exam4j.session.SessionManager;
import org.yankun.exam4j.session.UserSessionData;
import org.yankun.exam4j.web.thread.ThreadContextManager;


public class ThreadContextInterceptor implements HandlerInterceptor, ApplicationContextAware, InitializingBean {
	
	ApplicationContext ac;
	ThreadContextManager threadContextManager;

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		threadContextManager.unregisterContext();
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object object) throws Exception {
		HttpSession session = request.getSession(false);
		if (SessionManager.isLogon(session)) {
			UserSessionData usd =  SessionManager.getSessionData(session);
			threadContextManager.registerContext(usd.getUserId(), usd.getUsername());
		}
		return true;
	}

	@Override
	public void setApplicationContext(ApplicationContext ac)
			throws BeansException {
		this.ac = ac;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.threadContextManager = ac.getBean(ThreadContextManager.class);
		
	}

}
